package com.tao.basegreendaomanager;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import org.greenrobot.greendao.AbstractDaoMaster;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseOpenHelper;

import java.util.HashMap;
import java.util.Map;

/**
 * reate by tao on{DATE}
 */
public abstract class BaseGreendaoManager<M extends AbstractDaoMaster, S extends AbstractDaoSession, H extends DatabaseOpenHelper> {

    public Context context = null;
    Map<String, S> daoSession = new HashMap<>();


    public void initGreendao(Context context, DbConfig[] configArray) {
        this.context = context;

        for (DbConfig dbConfig : configArray) {
            addDaosession(dbConfig);
        }
    }

    public void addDaosession(DbConfig dbConfig) {
        addDaosession(dbConfig.dbName, dbConfig.dbPassword, dbConfig.dbEntityClass);
    }

    public void addDaosession(String dbName, String password, Class[] classs) {
        if (daoSession.containsKey(dbName)) {
            return;
        }
        H devOpenHelper = myGreenDaoDevHelper(dbName, classs);
        M daoMaster = daoMaster(dbName, (null == password || password.isEmpty()) ? devOpenHelper.getWritableDb() : devOpenHelper.getEncryptedWritableDb(password));
        daoSession.put(dbName, newSession(dbName, daoMaster));
    }

    public S newSession(String dbName, M daoMaster) {
        return (S) daoMaster.newSession();
    }

   public abstract M daoMaster(
            String dbName,
            Database database
    ) ;

    public  abstract H myGreenDaoDevHelper(
            String dbName,
            Class[] classs
    ) ;

    public S getDaoSession(String dbName) {
        return daoSession.get(dbName);
    }

  public   static class DbConfig {
        public DbConfig(String dbName, Class[] dbEntityClass, String dbPassword) {
            this.dbName = dbName;
            this.dbEntityClass = dbEntityClass;
            this.dbPassword = dbPassword;
        }

        public DbConfig(String dbName, Class[] dbEntityClass) {
            this.dbName = dbName;
            this.dbEntityClass = dbEntityClass;
          
        }

        String dbName = "";
        Class[] dbEntityClass;
        String dbPassword = "";
    }


}
